package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //1 获取请求参数 username和password，并封装成user对象
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2 调用service层的login方法，得到新的user对象
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(username, password);
        //3 判断如果user!=null,说明登录成功，将user保存到session
        if (user != null){
                req.getSession().setAttribute("user",user);
                resp.getWriter().write("true");
        }else {
                resp.getWriter().write("false");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
